import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  Image,
  Modal,
  DatePicker,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { text_check, post_axios, show_img_url, kind_status } from "../../utils";
import ChooseWares from "../../modules/chooseWares/index";

export default function VisionCloudWalkGoods(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { Option } = Select;
  const { confirm } = Modal;
  const { actions, setSpinning } = props;

  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [name_search, setName_search] = useState("");
  const [barcode_search, setBarcode_search] = useState("");
  const [status, setStatus] = useState("");
  const [goods_list, setGoods_list] = useState([]);

  const getData = async (newPage, newRows, newBar_lib) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      barcode: barcode_search,
      name: name_search,
      status: status,
    };
    setSpinning(true);
    let res = await post_axios("vision_cloud_walk_goods", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    const receiveRows = res.data_rows.rows.map((item) => {
      item["pic"] = show_img_url(item, local_company_object.company);
      return item;
    });
    setGoods_list(receiveRows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("goods.goods_name"),
      dataIndex: "name",
      align: "center",
    },
    {
      title: t("goods.goods_image"),
      align: "center",
      render: (_, record) => (
        <>
          {record.pic && record.pic.length !== 0 ? (
            <Image className="table_img" src={record.pic} />
          ) : (
            ""
          )}
        </>
      ),
    },
    {
      title: t("goods.goods_barcode"),
      dataIndex: "barcode",
      align: "center",
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.barcode);
    setclickRow(row);
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey("");
    setclickRow([]);
    getData(page, rows);
  };

  const [choose_goods_show, setChoose_goods_show] = useState(false);
  const add_goods_dialog_show = async () => {
    setChoose_goods_show(true);
  };
  // 点击选择商品
  const choose_goods_btn_func = async (value) => {
    value = Object.assign(value, {
      company_id: local_company_object.id,
      company: local_company_object.company,
    });
    let res = await post_axios("vision_cloud_walk_goods", "m_add", value);
    if (!res) return;
    message.success({
      content: t("common.add_scuuess"),
    });
    //setChoose_goods_show(false);
  };
  const delete_goods = () => {
    if (clickRowKey === "") {
      message.warning({
        content: t("goods.choose_one_customer"),
      });
      return;
    }
    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          {t("goods.sure_to_delete_goods")}
          <strong> {clickRow.name}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          merchantSkuCode: clickRow.barcode,
          company_id: local_company_object.id,
          company: local_company_object.company,
          id: clickRow.id,
        };
        let res = await post_axios("vision_cloud_walk_goods", "m_del", upMsg);
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const [sync_goods_show, setSync_goods_show] = useState(false);
  const [sync_time_plan, setSync_time_plan] = useState("");
  const sync_goods = () => {
    setSync_goods_show(true);
  };
  const sync_goods_confirm = async () => {
    let upMsg = {
      time_plan: new Date(sync_time_plan).getTime(),
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("vision_cloud_walk_goods", "m_sync", upMsg);
    if (!res) return;
    message.success({
      content: t("common.success"),
    });
    setSync_goods_show(false);
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight = document.getElementsByClassName(
        "vision_cloud_walk_goods"
      )[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 110;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <>
      <div className="vision_cloud_walk_goods modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div className="ipt_box_title">{t("goods.goods_name")}</div>
            <Input
              placeholder=" "
              value={name_search}
              size="small"
              allowClear={true}
              onChange={(e) => setName_search(e.target.value)}
            />
          </div>
          <div className="ipt_box">
            <div className="ipt_box_title">{t("goods.goods_barcode")}</div>
            <Input
              placeholder=" "
              value={barcode_search}
              size="small"
              allowClear={true}
              onChange={(e) => setBarcode_search(e.target.value)}
            />
          </div>
          <div className="ipt_box">
            <div className="ipt_box_title">{t("common.status")}</div>
            <Select
              size="small"
              placeholder=" "
              value={status}
              onChange={(value) => setStatus(value)}
            >
              {Object.keys(kind_status).map((key) => {
                return (
                  <Option value={key} key={key}>
                    {text_check(kind_status[key])}
                  </Option>
                );
              })}
            </Select>
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={add_goods_dialog_show}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_sync") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={sync_goods}
              >
                {text_check(user_power_lang["m_sync"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_goods}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            id="page-child-table"
            style={{
              width: "99.9vw",
            }}
          >
            <Table
              dataSource={goods_list}
              size="small"
              bordered
              columns={columns}
              rowKey="barcode"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.id == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>
      {choose_goods_show ? (
        <ChooseWares
          local_company_object={local_company_object}
          setSpinning={setSpinning}
          tableHeight={tableHeight}
          choose_goods_show={choose_goods_show}
          setChoose_goods_show={setChoose_goods_show}
          choose_goods_btn_func={choose_goods_btn_func}
        />
      ) : (
        ""
      )}

      <Modal
        title={t("platform_manager.sync_goods")}
        open={sync_goods_show}
        onCancel={() => setSync_goods_show(false)}
        onOk={sync_goods_confirm}
        classNames={{
          body: "edit_dialog_body vision_cloud_walk_goods_dialog",
        }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box dialog_ipt_box_long">
          <div className="ipt_box_title">{t("platform_manager.time_plan")}</div>
          <DatePicker showTime onOk={(value) => setSync_time_plan(value)} />
        </div>
      </Modal>
    </>
  );
}
